﻿using AutoTask.Collect.Model;
using AutoTask.Model;
using AutoTask.Model.DB;
using RpcClient.Interface;
using RpcHelper;

namespace AutoTask.Collect.Collect
{
    [RpcClient.Attr.ClassLifetimeAttr(RpcClient.Attr.ClassLifetimeType.单例)]
    internal class AutoTaskLogCollect : IAutoTaskLogCollect
    {
        private IUnityCollect _Unity;

        private readonly DelayDataSave<AutoTaskLogModel> _SaveLog;

        public AutoTaskLogCollect(IUnityCollect unity)
        {
            this._Unity = unity;
            this._SaveLog = new DelayDataSave<AutoTaskLogModel>(_Save, 2, 10);
        }

        private void _Save(ref AutoTaskLogModel[] datas)
        {
            this._Unity.Resolve<DAL.IAutoTaskLogDAL>().Adds(datas);
        }

        public void Add(TaskExecLog[] logs, AutoTaskItem item, Guid taskId)
        {
            logs.ForEach(a =>
            {
                if (a.logRange == TaskLogRange.关闭日志 || 
                (a.isFail && (TaskLogRange.记录错误 & a.logRange) != TaskLogRange.记录错误) ||
                (!a.isFail && (TaskLogRange.记录成功 & a.logRange) != TaskLogRange.记录成功))
                {
                    return;
                }
                AutoTaskLogModel log = new AutoTaskLogModel()
                {
                    ItemId = item.Id,
                    EndTime = a.end,
                    BeginTime = a.begin,
                    ErrorId = a.errorId,
                    IsFail = a.isFail,
                    TaskId = taskId,
                    Result = a.result,
                    Id = Tools.NewGuid()
                };
                _SaveLog.AddData(log);
            });
        }

    }
}
